from flask import Blueprint, render_template, request, redirect, url_for
from models import HouseInfo
import math
list_page = Blueprint('list_page', __name__)


@list_page.route('/list/pattern/<int:page>')
def return_new_list(page):
    house_num = HouseInfo.query.count()

    total_num = math.ceil(house_num / 10)  # 计算总的页码数，向上取整
    result = HouseInfo.query.order_by(HouseInfo.publish_time.desc()).paginate(page=page, per_page=10)
    # 通过paginate()方法创建分页器，指定当前查询的页数为page，每页展示10条数据
    print("房源总数为:", house_num)
    print("房源页码数为:", total_num)
    print("当前房源信息为:", result)
    return render_template('list.html', house_list=result.items,
                           page_num=result.page, total_num=total_num)


@list_page.route('/query')
def search_txt_info():
    if request.args.get('addr'):
        addr = request.args.get('addr')
        result = HouseInfo.query.filter(
            HouseInfo.address == addr
        ).order_by(HouseInfo.publish_time.desc()).all()
        return render_template('search_list.html', house_list=result)
    if request.args.get('rooms'):
        rooms_info = request.args.get('rooms')
        result = HouseInfo.query.filter(
            HouseInfo.address == rooms_info
        ).order_by(HouseInfo.publish_time.desc()).all()
        return render_template('search_list.html', house_list=result)
    return redirect(url_for('index_page.index'))


def deal_title_over(word):
    if len(word) > 15:     # 当房源的标题长度值大于15时，用...替换
        return word[:15] + '...'
    else:
        return word


def deal_direction(word):
    if len(word) == 0 or word is None:  # 房源的从朝向、交通条件为空时
        return '暂无信息'
    else:
        return word


list_page.add_app_template_filter(deal_title_over, 'deal_title')
list_page.add_app_template_filter(deal_direction, 'deal_direction')
